﻿using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using Se.Framework.Common;
using Se.Framework.Common.Data;

namespace Trust.Casas.Model
{
    public abstract class RepositoryBase<T> : IRepository<T> where T : class
    {
        private DbContext Context
        {
            get
            {
                return ObjectRegistry.Current.Resolve<TrustContext>();
            }
        }

        public void AddExistingEntity(T entity)
        {
            Context.Entry(entity).State = EntityState.Unchanged;
        }

        public virtual IQueryable<T> Query()
        {
            return Context.Set<T>();
        }

        public virtual void Add(T entity)
        {
            Context.Set<T>().Add(entity);
        }

        public virtual void Update(T entity)
        {
            Context.Entry(entity).State = EntityState.Modified;
        }

        public virtual void Delete(T entity)
        {
            Context.Entry(entity).State = EntityState.Deleted;
        }

        public virtual T Find(params object[] keyValues)
        {
            return Context.Set<T>().Find(keyValues);
        }

        public virtual void ExecuteCommand(string procedureName, params DbParameter[] parameters)
        {
            var finalName = "";

            ((IObjectContextAdapter)Context).ObjectContext.CommandTimeout = 300;

            if (parameters == null || parameters.Count() == 0)
            {
                parameters = new List<DbParameter>().ToArray();
                finalName = procedureName;
            }
            else
            {
                finalName = string.Concat(procedureName, " ", string.Join(",", parameters.Select(p => p.ParameterName)));
            }

            Context.Database.ExecuteSqlCommand(finalName, parameters);
        }
    }
}